package com.loop.unclelend.ui.fragment

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.loop.unclelend.R
import com.loop.unclelend.app_config.UncleConfigs
import com.loop.unclelend.databinding.UiPageLoanStatusBinding
import com.loop.unclelend.pro.ProFragment
import com.loop.unclelend.ui.adapter.Adapter_Loan_Details_Account
import com.loop.unclelend.ui.presenter.Pre_Loan_Status
import com.loop.unclelend.ui.view.IView_Loan_Status
import com.loop.unclelend.utils.DensityUtils
import com.loop.unclelend.utils.decoration.LinearSpacingItemDecoration
import com.loop.unclelend.utils.dialog.Dialog_BindCard
import com.loop.unclelend.utils.dialog.Dialog_BindCard_Delete
import com.loop.unclelend.utils.dialog.Dialog_BindCard_OnlyOneWarning
import com.loop.unclelend.utils.dialog.Dialog_BindCard_Other
import com.loop.unclelend.utils.event.UncleEventData
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import com.loop.unclelend.utils.helper.CustomProcessHelper
import com.loop.unclelend.utils.helper.UncleStatusHelper
import org.json.JSONObject
import java.math.BigDecimal

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/10 15:07
 * @Annotation：审核中、放款中、已拒绝
 */
class Fm_Loan_Status: ProFragment(), IView_Loan_Status {
    lateinit var binding: UiPageLoanStatusBinding
    private var presenter: Pre_Loan_Status? = null

    private var accountAdapter: Adapter_Loan_Details_Account? = null

    private var eventRemark = ""
    override fun getUncleRootView(inflater: LayoutInflater): View {
        binding = UiPageLoanStatusBinding.inflate(inflater)
        return binding.root
    }

    override fun initUncleView() {
        initRefreshLayout()
        initRecyclerViews()
    }

    override fun initUncleListener() {
    }

    override fun initUncleData() {
        if (presenter == null){
            presenter = Pre_Loan_Status(this)
        }
        showUncleLoading()
        presenter!!.checkUncleStatusAction()
    }


    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        binding.layoutRefresh.setEnableLoadMore(false)
        binding.layoutRefresh.setEnableAutoLoadMore(false)
        binding.layoutRefresh.setOnRefreshListener {
            getAct().publishEventData(UncleEventData(UncleEventData.TYPE.UNCLE_PROCESS_REFRESH))
        }
        binding.layoutRefresh.setOnLoadMoreListener {
            binding.layoutRefresh.finishLoadMore()
        }
    }

    /**
     * 初始化Views
     */
    private fun initRecyclerViews(){
        binding.rvAccount.isNestedScrollingEnabled = false
        binding.rvAccount.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = DensityUtils.dp2px(12f)
        binding.rvAccount.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.rvAccount.layoutManager = layoutManager
        accountAdapter = Adapter_Loan_Details_Account(binding.rvAccount)
        binding.rvAccount.adapter = accountAdapter!!
        binding.rvAccount.itemAnimator = DefaultItemAnimator()
        accountAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val item = accountAdapter!!.getItem(position)
            when(childView.id){
                R.id.img_delete -> {//删除
                    showDeleteDialog(position)
                }
            }
        }
    }

    /**
     * 通用View
     */
    override fun showStatusCommonViews(obj: JSONObject) {
        binding.txtAmount.text = "${obj.optString("currency")} ${BigDecimal(obj.optString("amount")).stripTrailingZeros().toPlainString()}"
        binding.txtTerm.text = String.format(getString(R.string.loan_term_value),obj.optString("days"))
    }

    /**
     * 审核中
     */
    override fun showStatusAuditViews() {
        binding.imgStatus.setImageResource(R.mipmap.icon_loan_audit)
        binding.txtAuditTime.visibility = View.VISIBLE
        val showKey = getString(R.string.loan_audit_time_value)
        val showText = String.format(getString(R.string.loan_audit_time),showKey)
        val startIndex = showText.indexOf(showKey)
        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFEC273A")), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.txtAuditTime.text = spString

        binding.txtAuditTips.visibility = View.VISIBLE
        binding.imgLable.setImageResource(R.drawable.uncle_loan_audit_lable)
        binding.txtStatus.text = getString(R.string.loan_audit)
        binding.txtReapplyAfterTime.visibility = View.GONE
        binding.layoutFrTips.visibility = View.GONE

        //账户列表
        presenter!!.requestAccountListAction()
        binding.layoutAccount.visibility = View.VISIBLE
        if (UncleConfigs.isFrench()){
            binding.btnAdd.visibility = View.VISIBLE
        } else {
            binding.btnAdd.visibility = View.GONE
        }
    }

    /**
     * 放款中
     */
    override fun showStatusLendingViews() {
        binding.imgStatus.setImageResource(R.mipmap.icon_loan_lending)
        binding.txtAuditTime.visibility = View.GONE
        binding.txtAuditTips.visibility = View.GONE
        binding.imgLable.setImageResource(R.drawable.uncle_loan_lending_lable)
        binding.txtStatus.text = getString(R.string.loan_lending)
        binding.txtReapplyAfterTime.visibility = View.GONE

        //账户列表
        presenter!!.requestAccountListAction()
        binding.layoutAccount.visibility = View.VISIBLE
        //非法语地区不显示添加账户按钮
        if (UncleConfigs.isFrench()){
            binding.btnAdd.visibility = View.VISIBLE
            binding.layoutFrTips.visibility = View.VISIBLE
        } else {
            binding.btnAdd.visibility = View.GONE
            binding.layoutFrTips.visibility = View.GONE
        }
    }

    /**
     * 已拒绝
     */
    override fun showStatusRejectedViews() {
        binding.imgStatus.setImageResource(R.mipmap.icon_loan_rejected)
        binding.txtAuditTime.visibility = View.GONE
        binding.txtAuditTips.visibility = View.GONE
        binding.imgLable.setImageResource(R.drawable.uncle_loan_rejected_lable)
        binding.txtStatus.text = getString(R.string.loan_rejected)
        binding.txtReapplyAfterTime.visibility = View.VISIBLE
        binding.txtReapplyAfterTime.text = String.format(getString(R.string.loan_rejected_reapply),CustomProcessHelper.getUncleApplyAgainDate())

        binding.layoutAccount.visibility = View.GONE
        binding.layoutFrTips.visibility = View.GONE
    }

    override fun showStatusRepayViews() {
        showUncleToast("show repay page")
    }

    /**
     * 账户列表
     */
    override fun showAccountList(accountList: ArrayList<JSONObject>) {
        accountAdapter!!.data = accountList
        val count = accountList.size

        if (UncleConfigs.isFrench()){
            /**
             * 法语地区 审核中 && 只有一个账户  提示新增绑卡
             */
            val applyStatus = CustomProcessHelper.getUncleApplyStatus()
            //审核中 && 只有一个账户
            if (UncleStatusHelper.StatusRepository(applyStatus,"").isReviewing() && count <= 1){
                showUncleAccountOnlyOneAddDialog()
            }

            //最多添加10个账户
            if (count >= 10){
                binding.btnAdd.isEnabled = false
                binding.btnAdd.visibility = View.GONE
            } else {
                binding.btnAdd.isEnabled = true
                binding.btnAdd.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showBindingAccountOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = Dialog_BindCard_Other(context,eventRemark,object : Dialog_BindCard_Other.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btn_confirm){//添加
                    presenter!!.requestBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 法语地区只有一个账户，提示新增绑卡
     */
    private fun showUncleAccountOnlyOneAddDialog(){
        val warningDialog = Dialog_BindCard_OnlyOneWarning(context,object : Dialog_BindCard_OnlyOneWarning.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btn_add){
                    showBinCardAddDialog()
                }
            }
        })
        warningDialog.show()
    }

    /**
     * 添加绑卡dialog
     */
    private fun showBinCardAddDialog(){
        val bindCardDialog = Dialog_BindCard(context,eventRemark,object : Dialog_BindCard.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                presenter!!.requestBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }

    /**
     * 删除提示
     */
    private fun showDeleteDialog(position: Int){
        val item = accountAdapter!!.getItem(position)
        item.put("walletLogo",item.optString("logo"))
        item.put("walletDesc",item.optString("name"))
        item.put("walletMobile",item.optString("account"))
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER_ACCOUNT_DELETE,item.optString("cardId"))
        val deleteDialog = Dialog_BindCard_Delete(context,eventRemark, object : Dialog_BindCard_Delete.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btn_submit){
                    presenter!!.requestDeleteAccountAction(item.optString("id"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(false)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    override fun hideUncleLoading() {
        super.hideUncleLoading()
        binding.layoutRefresh.finishRefresh()
    }

    override fun onUncleEvent(event: UncleEventData) {
        super.onUncleEvent(event)
        when(event.eventType){
            UncleEventData.TYPE.UNCLE_PROCESS_REFRESHED -> {
                presenter!!.checkUncleStatusAction()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${CustomProcessHelper.getUncleStatusRemark()} Page"
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.PAGE.UNCLE_PAGE_LOAN_COMMON_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.PAGE.UNCLE_PAGE_LOAN_COMMON_END,eventRemark)
    }
}